package com.rock.securityresearch.util


import java.time.{DayOfWeek, LocalDate}
import java.time.temporal.WeekFields
import java.util.Locale

object DateUtil {

    def getMostRecentFriday(date: LocalDate): LocalDate = {
        var current = date
        while (current.getDayOfWeek != DayOfWeek.FRIDAY) {
            current = date.minusDays(1)
        }
        current
    }

    def getMostRecentMonthEnd(date: LocalDate): LocalDate = {
        var current = date
        while (current.getDayOfMonth != 31) {
            current = date.minusDays(1)
        }
        current
    }

    

    def getWeekOfDate(date: LocalDate): Int = {
        date.get(WeekFields.of(Locale.ENGLISH).weekOfYear)
    }

    def groupBy(dates: List[LocalDate], groupFn: LocalDate => String): List[List[LocalDate]] = {
        dates.groupBy(groupFn).toList.map(e => e._2)
    }

    def groupByWeek(dates: List[LocalDate]): List[List[LocalDate]] = {
        groupBy(dates, date => s"${date.getYear}_${getWeekOfDate(date)}")
    }

    def groupByMonth(dates: List[LocalDate]): List[List[LocalDate]] = {
        groupBy(dates, date => s"${date.getYear}_${date.getMonth}")
    }

    def groupByYear(dates: List[LocalDate]): List[List[LocalDate]] = {
        groupBy(dates, date => s"${date.getYear}")
    }
}
